package com.ydm.restaurant.common.utils;

import io.minio.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

@Data
@AllArgsConstructor
@Slf4j
public class MinioUtil {

	private String endpoint;
	private String accessKeyId;
	private String accessKeySecret;
	private String bucketName;

	/**
	 * 文件上传
	 *
	 * @param file
	 * @param folderName
	 * @param objectName
	 * @return
	 */
	public String upload(MultipartFile file, String folderName, String objectName) {

		MinioClient minioClient = MinioClient.builder()
				.endpoint(endpoint)
				.credentials(accessKeyId,accessKeySecret)
				.build();

		try {

			boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
			if (!bucketExists){
//                如果不存在，就创建桶
				minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
			}

			// Upload the object to the bucket.

			String fullObjectName = folderName + "/" + objectName;
			minioClient.putObject(PutObjectArgs.builder()
					.bucket(bucketName) // 存储桶
					.object(fullObjectName) // 文件名
					.stream(file.getInputStream(), file.getSize(), -1) // 文件内容
					.contentType(file.getContentType()) // 文件类型
					.build());
			
		} catch (Exception e) {
			log.error("Error occurred: {}", e.getMessage());
		}

		// Construct the file access URL.
		StringBuilder stringBuilder = new StringBuilder(endpoint).append("/");
		stringBuilder.append(bucketName).append("/")
				.append(folderName).append("/")
				.append(objectName);

		log.info("文件上传到:{}", stringBuilder.toString());

		return stringBuilder.toString();

	}

	public void delete(String fullObjectName, String folderName) {
		MinioClient minioClient = MinioClient.builder()
				.endpoint(endpoint)
				.credentials(accessKeyId, accessKeySecret)
				.build();

		try {
			// 解析文件路径
			// 找到最后一个斜杠的位置
			int lastSlashIndex = fullObjectName.lastIndexOf("/");
			String objectName = fullObjectName.substring(lastSlashIndex + 1);

			// 删除对象
			minioClient.removeObject(RemoveObjectArgs.builder()
					.bucket(bucketName)
					.object(folderName + "/" + objectName)
					.build());
			log.info("文件删除成功: {}", fullObjectName);
		} catch (Exception e) {
			log.error("删除文件时出错: {}", e.getMessage());
		}
	}


}
